<template>
  <el-form ref="skuForm" label-width="80px" :model="skuInfo" :rules="rules">
    <el-form-item label="SPU名称">
      <span>{{ spuName }}</span>
    </el-form-item>
    <el-form-item label="SKU名称" prop="skuName">
      <el-input v-model="skuInfo.skuName" placeholder="请输入SKU名称" />
    </el-form-item>
    <el-form-item label="价格" prop="price">
      <el-input-number
        v-model="skuInfo.price"
        style="width: 100%"
        controls-position="right"
        :min="0"
      />
    </el-form-item>
    <el-form-item label="重量" prop="weight">
      <el-input-number
        v-model="skuInfo.weight"
        style="width: 100%"
        controls-position="right"
        :min="0"
      />
    </el-form-item>
    <el-form-item label="SKU描述" prop="skuDesc">
      <el-input v-model="skuInfo.skuDesc" type="textarea" placeholder="请输入SKU描述" />
    </el-form-item>
    <el-form-item label="平台属性" class="my_form_item" prop="skuAttrValueList">
      <el-row>
        <el-col v-for="attr,index in attrList" :key="attr.id" :md="8" :sm="12" :xs="24" class="el-sku-col">
          <el-form-item :label="attr.attrName">
            <el-select v-model="skuInfo.skuAttrValueList[index]">
              <el-option v-for="attrValue in attr.attrValueList" :key="attrValue.id" :value="`${attr.id}:${attr.attrName}:${attrValue.id}:${attrValue.valueName}`" :label="attrValue.valueName">{{ attrValue.valueName }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>

    <el-form-item label="销售属性" prop="skuSaleAttrValueList">
      <el-row>
        <el-col v-for="spuSaleAttr,index in spuSaleAttrList" :key="spuSaleAttr.id" :md="8" :sm="12" :xs="24" class="el-sku-col">
          <el-form-item :label="spuSaleAttr.saleAttrName">
            <el-select v-model="skuInfo.skuSaleAttrValueList[index]">
              <el-option v-for="spuSaleAttrValue in spuSaleAttr.spuSaleAttrValueList" :key="spuSaleAttrValue.id" :value="`${spuSaleAttr.id}:${spuSaleAttr.saleAttrName}:${spuSaleAttrValue.id}:${spuSaleAttrValue.saleAttrValueName}`" :label="spuSaleAttrValue.saleAttrValueName">{{ spuSaleAttrValue.saleAttrValueName }}</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form-item>
    <el-form-item label="图片列表" prop="skuImageList">
      <el-table
        ref="multipleTable"
        border
        tooltip-effect="dark"
        style="width: 100%"
        :data="spuImageList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片">
          <template v-slot="{row}"><img style="width:100px; height: 100px" :src="row.imgUrl" :alt="row.imgName"></template>
        </el-table-column>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="address" label="操作" show-overflow-tooltip>
          <template v-slot="{ row }">
            <el-button
              v-if="row.isDefault === '0'"
              type="primary"
              @click="setDefault(row)"
            >设置默认图片</el-button>
            <el-button v-else type="success" disabled>默认图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">确定</el-button>
      <el-button @click="$emit('update:visible', 1)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { mapState } from 'vuex'
import { reqGetSpuImageList, reqGetSpuSaleAttrList } from '@/api/product/spu'
import { reqGetAttrList } from '@/api/product/attr'
import { reqSaveSkuInfo } from '@/api/product/sku'
export default {
  name: 'SaveSku',
  data() {
    const skuAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个平台属性')
        return
      }
      callback()
    }
    const skuImageListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择至少一张图片')
        return
      }
      callback()
    }
    const skuSaleAttrValueListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请选择一个销售属性')
        return
      }
      callback()
    }
    return {
      num: 0,
      attrList: [], // 平台属性
      spuImageList: [],
      spuSaleAttrList: [],
      skuInfo: {
        // spu名称
        skuName: '',
        // 价格
        price: 0,
        // 重量
        weight: 0,
        // 描述
        skuDesc: '',
        // 默认图片
        skuDefaultImg: '',
        // 平台属性
        skuAttrValueList: [],
        // 图片列表
        skuImageList: [],
        // 销售属性列表
        skuSaleAttrValueList: []
      },
      rules: {
        skuName: [
          { required: true, message: '请输入SKU名称', trigger: 'blur' }
        ],
        price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
        skuDesc: [
          { required: true, message: '请输入SKU描述', trigger: 'blur' }
        ],
        skuImageList: [
          {
            required: true,
            validator: skuImageListValidate,
            trigger: 'change'
          }
        ],
        skuAttrValueList: [
          {
            required: true,
            validator: skuAttrValueListValidate,
            trigger: 'change'
          }
        ],
        skuSaleAttrValueList: [
          {
            required: true,
            validator: skuSaleAttrValueListValidate,
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {
    ...mapState('category', ['category1Id', 'category2Id', 'category3Id']),
    ...mapState('spu', ['spuId', 'spuName'])
  },
  async mounted() {
    const { category1Id, category2Id, category3Id } = this
    const [responseSpuImageList, responseSpuSaleAttrList, responseAttList] = await Promise.allSettled([reqGetSpuImageList(this.spuId), reqGetSpuSaleAttrList(this.spuId), reqGetAttrList({ category1Id, category2Id, category3Id })])
    console.log(responseAttList)
    if (responseAttList.status === 'fulfilled') {
      this.attrList = responseAttList.value.data
    }
    if (responseSpuImageList.status === 'fulfilled') {
      this.spuImageList = responseSpuImageList.value.data.map(item => {
        return {
          ...item,
          isDefault: '0'
        }
      })
    }
    if (responseSpuSaleAttrList.status === 'fulfilled') {
      this.spuSaleAttrList = responseSpuSaleAttrList.value.data
    }
  },
  methods: {
    // 3.提交校验
    submitForm() {
      this.$refs.skuForm.validate(async(valid) => {
        if (valid) {
          if (!this.skuInfo.skuDefaultImg) {
            this.$message.error('请选择默认图片')
            return
          }
          const {
            skuName,
            price,
            skuDesc,
            weight,
            skuDefaultImg,
            skuImageList,
            skuAttrValueList,
            skuSaleAttrValueList
          } = this.skuInfo
          const result = await reqSaveSkuInfo({
            skuName,
            price,
            skuDesc,
            weight,
            skuDefaultImg,
            skuImageList,
            skuAttrValueList: skuAttrValueList.filter(Boolean).map((item) => {
              const [attrId, attrName, valueId, valueName] = item.split(':')
              return {
                attrId,
                attrName,
                valueId,
                valueName
              }
            }),
            skuSaleAttrValueList: skuSaleAttrValueList
              .filter(Boolean)
              .map((item) => {
                const [
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                ] = item.split(':')
                return {
                  saleAttrId,
                  saleAttrName,
                  saleAttrValueId,
                  saleAttrValueName
                }
              }),
            spuId: this.spuId,
            category3Id: this.category3Id
          })
          // console.log(result);
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '添加sku成功...'
            })
            this.$emit('update:visible', 1)
          } else {
            this.$message({
              type: 'error',
              message: '添加sku失败...'
            })
          }
        }
      })
    },
    // 2.收集选中的图片数据
    handleSelectionChange(val) {
      // console.log(val)
      this.skuInfo.skuImageList = val
    },
    // 1.设置默认图片
    setDefault(row) {
      this.spuImageList.forEach(item => {
        item.isDefault = '0'
      })
      row.isDefault = '1'
      this.skuInfo.skuDefaultImg = row.imgUrl
    }
  }
}
</script>

<style lang="scss">
.my_form_item{
    .el-form-item {
      margin-bottom: 20px;
    }
  }
  .el-input {
    .el-input__inner{
      text-align: left;
    }
  }
</style>
